function timestampToCountdown(timestamp, formatStr = "hh:mm:ss", formatAdditional) {
    const timestampNum = parseInt(timestamp);
    const rule = {
        "d+": Math.floor(timestampNum / 1000 / 60 / 60 / 24), // 日
        "h+": Math.floor(timestampNum / 1000 / 60 / 60 % 24), // 时
        "m+": Math.floor(timestampNum / 1000 / 60 % 60), // 分
        "s+": Math.floor(timestampNum / 1000 % 60), // 秒
        "S": Math.floor(timestampNum % 1000) // 毫秒
    };

    let formatRes = rule["d+"] > 0 ? formatAdditional || formatStr : formatStr;

    for (let analytical in rule) {
        if (new RegExp("(" + analytical + ")").test(formatRes)) {
            formatRes = formatRes.replace(RegExp.$1, RegExp.$1.length === 1 ? rule[analytical] : ("00" + rule[
                analytical]).substr(("" + rule[analytical]).length));
        }
    }

    return formatRes;
}

function throttle(fn, delay = 200) {
    let canRun = true;
    return function() {
        if (!canRun) return;
        canRun = false;
        setTimeout(() => {
            fn.apply(this, arguments);
            canRun = true;
        }, delay);
    };
}
/**
 * 节流函数
 * @param {Function} fn 节流回调函数
 * @param {Number} delay 延迟时间
 * @returns
 */
function throttle2(fn, delay = 200) {
    let canRun = true;
    return function() {
        if (!canRun) return;
        fn.apply(this, arguments);
        canRun = false;
        setTimeout(() => {
            canRun = true;
        }, delay);
    };
}

/**
 * 防抖函数
 * @param {Function} fn 防抖回调眼熟
 * @param {Number} delay 防抖延迟时间
 * @returns
 */
function debounce(fn, delay = 200) {
    let timer = null;
    return function() {
        clearTimeout(timer)
        timer = setTimeout(() => {
            fn.apply(this, arguments)
            timer = null
        }, delay)
    }
}

function getImgTemp(src) {
    return new Promise((resolve, reject) => {
        uni.getImageInfo({
            src,
            success(res) {
                resolve(res)
            },
            fail(err) {
                uni.hideLoading()
                reject(err)
            },
        })
    })
}


async function saveImgToPhotosAlbum(filePath, isOnlinePath, isVideo) {
    const uniApiToPromise = (api, params) => {
        return new Promise((resolve, reject) => {
            uni[api]({
                ...params,
                success(res) {
                    resolve(res)
                },
                fail(err) {
                    reject(err)
                }
            })
        })
    }

    const loadFile = (url) => {
        return new Promise((resolve, reject) => {
            uni.getImageInfo({
                src: url,
                success(res) {
                    resolve(res.path)
                },
                fail(err) {
                    uni.showToast({ title: '图片获取失败', duration: 3000, icon: 'none' });
                }
            })
        });
    }

    const saveImg = (filePath) => {
        if(isVideo) {
            uni.saveVideoToPhotosAlbum({
                filePath: filePath,
                success() {
                    return uni.showToast({ title: '保存成功', duration: 3000, icon: 'none' });
                },
                fail(err) {
                    console.log(err);
                    return uni.showToast({ title: '保存失败', duration: 3000, icon: 'none' });
                }
            })
        } else {
            uni.saveImageToPhotosAlbum({
                filePath: filePath,
                success() {
                    return uni.showToast({ title: '图片保存成功', duration: 3000, icon: 'none' });
                },
                fail(err) {
                    console.log(err);
                    return uni.showToast({ title: '保存失败', duration: 3000, icon: 'none' });
                }
            })
        }
    }

    uni.showLoading({ mask: true, title: '正在保存...' });
    if (isOnlinePath) {
        filePath = await loadFile(filePath)
    }

    let auth;
    try {
        auth = await uniApiToPromise('getSetting')
    } catch (err) {
        return uni.showToast({ title: '获取授权信息失败', duration: 3000, icon: 'none' });
    }
    if (auth.authSetting['scope.writePhotosAlbum'] === undefined) {
        // 从来没有获取过授权的情况
        try {
            await uniApiToPromise("authorize", {
                scope: 'scope.writePhotosAlbum'
            });
        } catch (err) {
            return uni.showToast({ title: '保存失败,无法获取相册授权', duration: 3000, icon: 'none' });
        }
        saveImg(filePath)
    } else if (auth.authSetting['scope.writePhotosAlbum'] === false) {
        // 授权拒绝
        const au = await uniApiToPromise("openSetting");
        if (au.authSetting['scope.writePhotosAlbum']) {
            saveImg(filePath)
        } else {
            return uni.showToast({ title: '保存失败,无法获取相册授权', duration: 3000, icon: 'none' });
        }
    } else {
        // 已经授权过同意
        saveImg(filePath)
    }



}

export {
    getImgTemp,
    timestampToCountdown,
    throttle,
    throttle2,
    debounce,
    saveImgToPhotosAlbum
}
